package com.basis.controller.api;

import java.util.HashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.basis.contants.UserStatusEnum;
import com.basis.entity.SysUser;
import com.basis.entity.baseEntity.R;
import com.basis.service.ISysUserService;
import com.basis.utils.CryptoUtils;
import com.basis.utils.JwtTokenUtil;

/**
 * api接口
 *
 * @author lxd
 */

@RestController
@RequestMapping(value = "/api")
public class ApiController {

	@Autowired
	private ISysUserService sysUserService;

	/**
	 * api鉴权
	 *
	 * @param username
	 * @param password
	 * @return
	 */
	@GetMapping(value = "/login")
	public Object auth(@RequestParam("username") String username, @RequestParam("password") String password) {
//        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password.toCharArray());
		QueryWrapper<SysUser> query = new QueryWrapper<SysUser>();
		query.eq("user_name", username);
		SysUser sysUser = sysUserService.getOne(query);
		if (sysUser != null) {
			if (!CryptoUtils.verify(password, sysUser.getUserPwd())) {
				return R.error("密码错误");
			}
			if (sysUser.getStatus().equals(UserStatusEnum.UNENABLE.getCode())) {
				return R.error("该账户已被禁用,请联系管理员");
			}
			HashMap<String, Object> result = new HashMap<>();
			result.put("token", JwtTokenUtil.generateToken(String.valueOf(sysUser.getId())));
			return result;
		} else {
			return R.error("账号密码错误");
		}
	}

	/**
	 * 测试接口是否走鉴权
	 */
	@RequestMapping(value = "/test", method = RequestMethod.POST)
	@Cacheable(value = "test", key = "'testKey111'")
	public Object test() {
		System.out.println("查询数据库");
		return R.success("登入成功");
	}

}
